package dale.web.essay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import dale.web.essay.model.Essay;
import dale.web.essay.model.EssayType;
import dale.web.essay.service.EssayService;

@Controller
@RequestMapping("/essay")
@SessionAttributes("essay")
public class EssayPostController {

	@Autowired
	private EssayService service;

	@RequestMapping(value = "/essayCreate", method = RequestMethod.GET)
	public Essay create() {
		return new Essay();
	}

	@RequestMapping(value = "/essayCreate", method = RequestMethod.POST)
	public String create(@ModelAttribute @Validated Essay item, Errors errors, SessionStatus status, RedirectAttributes redirectAttributes) {
		if (errors.hasErrors())
			return "/essay/essayCreate";
		if (service.create(item) != 1) {
			throw new RuntimeException("Nothing inserted.");
		} else {
			status.setComplete();
			redirectAttributes.addFlashAttribute("msg", "Created sucessfully.");
			
			return "redirect:/essay/essayDetail?no=" + item.getNo();
		}
	}

	@RequestMapping(value = "/essayModify", method = RequestMethod.GET)
	public Essay modify(@RequestParam Integer no) {
		return service.detail(no);
	}

	@RequestMapping(value = "/essayModify", method = RequestMethod.POST)
	public String modify(@ModelAttribute @Validated Essay item, Errors errors, SessionStatus status, RedirectAttributes redirectAttributes) {
		if (errors.hasErrors()) {
			return "/essay/essayModify";
		}

		if (service.modify(item) != 1) {
			throw new RuntimeException("Nothing updated.");
		}

		status.setComplete();
		redirectAttributes.addFlashAttribute("msg", "Modified sucessfully.");

		return "redirect:/essay/essayDetail?no=" + item.getNo();
	}

	@ModelAttribute("typeItems")
	public EssayType[] getTypeItems() {
		return EssayType.values();
	}
	
}
